﻿using ImModels.View;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json;

namespace ImClientApi.Utils
{
    public class JwtHepler
    {
        /// <summary>
        /// 
        /// </summary>
        public static string jwtkey = ConfigUtils.GetConfigToString("JwtSetting:JwtKey");
        /// <summary>
        /// 
        /// </summary>
        public static string jwtuser = ConfigUtils.GetConfigToString("JwtSetting:JwtIssuer");
        /// <summary>
        /// 
        /// </summary>
        public static string jwtaudit = ConfigUtils.GetConfigToString("JwtSetting:JwtAudience");
        /// <summary>
        /// 
        /// </summary>
        public static string jwtdays = ConfigUtils.GetConfigToString("JwtSetting:JwtExpires");


        /// <summary>
        /// 创建jwttoken
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="exdays">过期时间 天数0读取配置文件</param>
        /// <returns></returns>
        public static string BuildJwtToken(IEnumerable<Claim> claims, int exdays = 0)
        {
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtkey));

            if (exdays == 0)
            {
                exdays = int.Parse(jwtdays);
            }
            DateTime expiresAt = DateTime.Now.AddDays(exdays);

            //将用户信息添加到 Claim 中
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);

            identity.AddClaims(claims);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),//创建声明信息
                Issuer = jwtuser,//Jwt token 的签发者
                Audience = jwtaudit,//Jwt token 的接收者
                NotBefore = DateTime.Now,
                Expires = expiresAt,//过期时间
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256)//创建 token
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }

        /// <summary>
        /// 验证签名是否正确
        /// 1.验证Token是否是符合要求的标准 Json Web 令牌
        /// 2.
        /// </summary>
        /// <param name="token"></param>
        /// <param name="enterpriseId">企业ID</param>
        /// <returns>返回 success 表示成功 其他为错误信息</returns>
        public static string IsSuccessReInfo(string token)
        {
            if (string.IsNullOrWhiteSpace(token) || token.Length < 7)
                return "Unanthorized";

            if (!token.Substring(0, 6).Equals(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme))
                return "Token Error.";

            token = token.Substring(7);

            bool isCan = new JwtSecurityTokenHandler().CanReadToken(token);

            //if (isCan)
            //{
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm alg = new HMACSHA256Algorithm();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);

            try
            {
                var json = decoder.Decode(token, jwtkey, true);

                var jwtUsers = JsonSerializer.Deserialize<JwtUserInfo>(json);

                if (!string.IsNullOrWhiteSpace(jwtUsers?.EnterpriseId))
                {
                    //校验通过，返回解密后的字符串
                    return "success";
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "Token NotCheck EnterPrise";
            //}
            //return isCan ? "success" : "Token Error.";
        }

        /// <summary>
        /// 获取认证信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static JwtUserInfo GetSignInfo(string token)
        {
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm alg = new HMACSHA256Algorithm();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);

            var json = decoder.Decode(token?.Replace("Bearer ", ""), jwtkey, true);
            //校验通过，返回解密后的字符串
            return JsonSerializer.Deserialize<JwtUserInfo>(json);
        }
    }
}
